package com.cyzy.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * 用于生成校验token的工具类
 */
@Component
public class TokenUtils {

    @Value("${token.secret_key}")
    private String sing;

    @Value("#{${token.expiration_time}}")
    private Integer  time;

    // 从令牌中获取用户名
    public  String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    // 通用方法，从令牌中获取指定声明
    public  <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    // 检查令牌是否过期
    private  boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }



    // 获取令牌过期时间
    public  Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    // 验证令牌是否有效
//    public  boolean validateToken(String token, UserEntity user) {
//        final String userAcc = getUsernameFromToken(token);
//        return (userAcc.equals(user.getUserAcc()) &&!isTokenExpired(token));
//    }

    public  boolean validateToken(String token) {
        return !isTokenExpired(token);
    }


    // 解析令牌，获取所有声明
    private  Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(sing).parseClaimsJws(token).getBody();
    }

    // 获得令牌
    public  String generateToken(String acc){
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, acc);
    }

    public  String generateToken(String acc, Map<String, Object> mp){
        return doGenerateToken(mp, acc);
    }


    private  String doGenerateToken(Map<String, Object> claims, String subject){
            return Jwts.builder()
                    .setClaims(claims)
                    .setSubject(subject)
                    .setIssuedAt(new Date())  // 签发时间
                    .setExpiration(new Date(System.currentTimeMillis() + time))  // 过期时间
                    .signWith(SignatureAlgorithm.HS512, sing) // 签名算法 & 密钥
                    .compact();
    }

}
